<template>
    <div>
        <v-container>
            <v-row class="title_position showOrder">
                <v-col cols="6">
                    <v-text-field solo label="博客标题" hide-details v-model="articleTitle"></v-text-field>
                </v-col>
                <v-spacer></v-spacer>
                <v-col cols="2">
                    <v-select dense
                              solo
                              :items="categoryData"
                              v-model="cateSelected"
                              item-text="cateName"
                              item-value="cid"
                              hide-details

                    >

                    </v-select>
                </v-col>
                <v-col cols="2">
                    <v-btn @click="saveAsDraft">保存草稿</v-btn>
                </v-col>
                <v-col cols="2">
                    <v-btn @click="saveArticle">发布文章</v-btn>
                </v-col>
            </v-row>
            <v-row class="pos">
                <v-col>
                    <mavon-editor ref=md @imgAdd="uploadImg" @save="saveArticle" @imgDel="delteImage"
                                  :scrollStyle="false"
                                  v-model="articleContent"/>

                </v-col>
            </v-row>
        </v-container>


    </div>


</template>

<script>
  /**
   * 后端编辑文章或者新建文章页面
   */
  export default {
    name: 'Ariticle',
    data() {
      return {
        articleId: '',
        articleTitle: '',
        articleContent: '',
        categoryData: [],
        cateSelected: ''
      }
    },
    methods: {
      /**
       * 将文章内容保存成草稿,传入的参数是draft字段
       */
      async saveAsDraft() {
        if (this.$route.path != '/manager/article/create') {
          this.updateArticleAsArticleOrDraft('draft')
        } else {
          this.uploadArticle('draft');
        }
      },
      /**
       * 上传图片
       */
      async uploadImg(pos, $file) {
        // 第一步.将图片上传到服务器.
        let formdata = new FormData();
        formdata.append('image', $file);
        try {
          const {data: res} = await  this.$http({
            url: '/manager/articles/images',
            method: 'post',
            data: formdata,
            headers: {'Content-Type': 'multipart/form-data'},
          })
          if (res.errorCode == 200) {
            alert('图片上传成功');
            this.$refs.md.$img2Url(pos, res.data);
            console.log(pos);
          } else {
            alert(res.message);
          }
        } catch (e) {
          alert('图片上传失败');
        }
      },
      /**
       * 删除上传的图片
       */
      async delteImage(pos) {
        const {data: res} = await  this.$http.post('/manager/articles/del', {
          fileUrl: pos[0]
        })
        alert('jjj')
        console.log(res);
      },
      /**
       * 发布文章
       */
      saveArticle() {
        if (this.$route.path != '/manager/article/create') {
          this.updateArticleAsArticleOrDraft('article')
        } else {
          this.uploadArticle('article');
        }
      },
      /**
       * 修改文章将文章保存为草稿或正式文章
       */
      async updateArticleAsArticleOrDraft(articleType) {
        if (this.cateSelected == '') {
          alert('请选择类别')
        }
        console.log('修改文章到草稿');
        console.log(this.categoryData);
        console.log(this.cateSelected);

        try {
          const {data: res} = await this.$http.put('/manager/articles', {
            articleId: this.articleId,
            articleContent: this.articleContent,
            articleTitle: this.articleTitle,
            articleType: articleType,
            articleCateId:this.cateSelected
          })
          if (res.errorCode == 200) {
            if (articleType === 'draft') {
              alert('已成功保存到草稿箱！');
              this.$router.push('/manager/article/draft/list');
            } else {
              alert('发布成功');
              this.$router.push('/');
            }
          } else if(res.errorCode===201) {
            // 当服务端返回登录信息失效的时候时候，重新进行登录
            this.$store.commit('setShowDialogToTrue');
          }else {
            alert('保存失败，请稍后重试！')
          }

        } catch (e) {
          console.log(e);
          alert('文章保存失败！')
        }
      },
      /**
       * 上传文章到服务器上
       * @param articleType 文件类型，draft：草稿，article：文章
       * @returns {Promise<void>}
       */
      async uploadArticle(articleType) {
        if (this.cateSelected == '') {
          alert('请选择类别')
        }
        try {
          console.log('所选取的类别id');
          console.log(this.cateSelected);
          const {data: res} = await this.$http.post('/manager/articles', {
            articleContent: this.articleContent,
            articleTitle: this.articleTitle,
            articleType: articleType,
            articleCateId: this.cateSelected
          })
          if (res.errorCode == 200) {
            if (articleType === 'draft') {
              this.$router.push('/manager/article/draft/list');
              alert('已成功保存到草稿箱！');
            } else {
              alert('发布成功');
              this.$router.push('/');
            }
          } else if(res.errorCode===201) {
           // 当服务端返回登录信息失效的时候时候，重新进行登录
            this.$store.commit('setShowDialogToTrue');
          }else {
            console.log(res);
            alert('保存失败，请稍后重试！')
          }

        } catch (e) {
          console.log(e);
          alert('文章保存失败！')
        }
      },
      //获取文章类别列表
      async getAllArticleCategories() {
        try {

          const {data: res} = await this.$http.get('/manager/categories');
          console.log('类别数据res');
          console.log(res);
          if (res.errorCode == 200) {

            this.categoryData = res.data;
          }else{
            alert('获取类别数据失败！')
          }
          console.log('类别数据cagegoryData');
          console.log(this.categoryData);

        } catch (e) {
          alert('查询文章类别失败，请重试！');
        }
      },
      /**
       * 根据id，获取文章详细内容
       * @param articleId
       * @returns {Promise<void>}
       */
      async getArticleById(articleId) {
        try {
          const {data: res} = await this.$http.get('articles/' + articleId, {
            params: {
              editFlag: true
            }
          });
          console.log(res);
          if (res.errorCode == 200) {
            // 获取到文章以后，设置文章内容，文章标题和文章所属类别
            this.articleContent = res.data.articleContent;
            this.articleTitle = res.data.articleTitle;
            // 当修改文章的时候，选中的类别对应的下标
            this.cateSelected = res.data.articleCateId
            console.log(this.cateSelected+"----");
            this.articleId = articleId;
          } else {
            alert('获取文章详细内容失败，请重试！')
          }
        } catch (e) {
          alert('获取文章内容失败，请重试！')
        }
      },
      // 返回类别所对应的下标，以1开始,我又调试了一下，没有问题是我弄错了。
      getCateIndex(cateId){
        for (let i = 0; i < this.categoryData.length; i++) {
          if (this.categoryData[i].cid===cateId){
            return i+1;
          }
        }
        return -100;
      }

    },
    created() {
      /**
       * 获取文章类别列表
       */
      this.getAllArticleCategories();
      /**
       * 获取文章详情，如果是创建文章的路径，不获取文章内容，否则就获取文章路径
       */
      if (this.$route.path != '/manager/article/create') {
        this.getArticleById(this.$route.params.id)
      }
    }


  }
</script>

<style scoped>
    .title_position {
        position: fixed;
        top: 70px;
        z-index: 1500 !important;
    }

    .pos {
        position: relative;
        top: 70px;
    }
</style>